package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.User;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.HierarchyService;
import com.sl.au.service.UserService;
import com.sl.utils.MsgHelper;

/**
 * 从用户的维度出发 查询网格相关信息
 * 
 * @author HeGuangChuan
 *
 */
@RestController
@RequestMapping("/ui/userDimension")
public class UserDimensionController extends BaseController {
	@Autowired
	private HierarchyService hierarchyService;
	@Autowired
	private UserService userService;
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping(value = "/unbind/{gridIds}/{userId}", method = RequestMethod.POST)
	public MsgHelper unbind(@PathVariable("gridIds") String gridIds, @PathVariable("userId") String userId) {
		gridIds = gridIds.substring(0, gridIds.length() - 1);
		// 之前绑定的网格
		// User user = userService.getRepository().findOne(userId);
		// Set<GridAreaInfo> grids = user.getGrids();
		String[] gridIdArr = gridIds.split(",");
		for (String g : gridIdArr) {
			GridAreaInfo findOne = gridAreaInfoService.getRepository().findOne(g);
			Set<User> users = findOne.getUsers();
			users.remove(userService.getRepository().findOne(userId));
			gridAreaInfoService.getRepository().save(findOne);
			/*
			 * if (grids.size() > 0 && grids != null) { for (GridAreaInfo gi :
			 * grids) { if (gi.getId().equals(findOne.getId())) {
			 * grids.remove(findOne); } } }
			 */
		}
		/*
		 * user.setGrids(grids); userService.getRepository().save(user);
		 */
		return MsgHelper.success();
	}

	@RequestMapping(value = "/bind/{userId}/{gridIds}", method = RequestMethod.GET)
	public MsgHelper bind(@PathVariable("userId") String userId, @PathVariable("gridIds") String gridIds) {
		gridIds = gridIds.substring(0, gridIds.length() - 1);
		// 先查出该用户原来绑定的网格
		User user = userService.getRepository().findOne(userId);
		Set<GridAreaInfo> oldGrids = user.getGrids();
		String[] gridIdArr = gridIds.split(",");
		for (String g : gridIdArr) {
			GridAreaInfo findOne = gridAreaInfoService.getRepository().findOne(g);
			oldGrids.add(findOne);
		}
		user.setGrids(oldGrids);
		userService.getRepository().save(user);
		return MsgHelper.success();
	}

	/**
	 * <pre>
		select g.id as id,g.gridIdentify as gridIdentify,g.gridName as gridName
		from sl_wcsi_gridarea g where g.id not IN
		(select grid_id from sl_wcsi_user_grid ug where ug.user_id=)
	  
		select count(*) count
		from sl_wcsi_gridarea g
		where g.id not IN
		(select grid_id from sl_wcsi_user_grid ug)
	 * </pre>
	 * 
	 * 
	 * 
	 */
	@RequestMapping(value = "/getGridUnbindUserPage", method = RequestMethod.POST)
	public Map<String, Object> getUnbindUserPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String uid = request.getParameter("uid");
		List<GridAreaInfo> infos = new ArrayList<>();

		int count = 0;
		if (StringUtils.hasText(uid)) {
			String sql = "select g.id as id,g.gridIdentify as gridIdentify,g.gridName as gridName" //
					+ " from sl_wcsi_gridarea g where g.id not IN" //
					+ "(select grid_id from sl_wcsi_user_grid ug where ug.user_id='" + uid + "')";
			StringBuilder sb = new StringBuilder();
			StringBuilder sb2 = new StringBuilder();

			if (StringUtils.hasText(key)) {
				sb.append(" and (g.gridIdentify like '%" + key + "%' or g.gridName like '%" + key + "%')");
				sb2.append(" and (g.gridIdentify like '%" + key + "%' or g.gridName like '%" + key + "%')");
			}
			sb.append(" limit " + start + "," + length);
			sql = sql + sb.toString();
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

			int i = 0;
			String id = "";
			String gridName = "";
			String gridIdentify = "";
			for (Map<String, Object> m : list) {

				GridAreaInfo g = new GridAreaInfo();
				Set<String> keys = m.keySet();
				for (String s : keys) {
					++i;
					if ("id".equals(s)) {
						id = m.get(s).toString();
						// u.setId(m.get(s).toString());
					}
					if ("gridIdentify".equals(s)) {
						if(m.get(s)!=null){
							gridIdentify = m.get(s).toString();
							// u.setName(m.get(s).toString());
						}else{
							gridIdentify="";
						}
						
					}
					if ("gridName".equals(s)) {
						if(m.get(s)!=null){
							gridName = m.get(s).toString();
						}else{
							gridName="";
						}
					}
					if (i % 3 == 0) {
						g.setId(id);
						g.setGridIdentify(gridIdentify);
						g.setGridName(gridName);
						infos.add(g);
						i = 0;
					}

				}
			}

			// count = userService.getUnbindGrid(key);
			sql = "select count(*) count from sl_wcsi_gridarea g where g.id not IN(select grid_id from sl_wcsi_user_grid ug where ug.user_id='"
					+ uid + "')";
			sql = sql + sb2.toString();
			List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
			for (Map<String, Object> m : queryForList) {
				Set<String> keySet = m.keySet();
				for (String s : keySet) {
					if ("count".equals(s)) {
						count = Integer.parseInt(m.get(s).toString());
					}
				}
			}
		}

		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/getGridBindUserPage", method = RequestMethod.POST)
	public Map<String, Object> getGridBindUserPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// userid
		String con = request.getParameter("con");
		List<GridAreaInfo> areaInfos = null;
		Integer count = null;
		if (StringUtils.hasText(con)) {
			areaInfos = gridAreaInfoService.getGridBindUserPageByKeyAndCon(start, length, key, con);
			count = gridAreaInfoService.getGridBindUserCountByCon(key, con);
		} else {
			areaInfos = gridAreaInfoService.getGridBindUserPageByKey(start, length, key, null, null);
			count = gridAreaInfoService.getGridBindUserCount(key);
		}

		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/getUserBindHierarchyPage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 带过来的key就是组织的id
		String con = request.getParameter("con");
		List<User> users = null;
		int count = 0;
		if (StringUtils.hasText(con)) {
			if (!"0".equals(key)) {
				// 指定组织的用户
				users = userService.getBindHierarchyUsersPageBykeyAndCon(start, length, key, con);
				count = userService.getBindHierarchyUsersCountByCon(key, con);
			} else {
				// 所有组织的用户
				users = userService.getAllBindHierarchyUsersByKeyAndCon(start, length, con);
				count = userService.getAllBindHierarchyUsersCountByKeyAndCon(con);
			}

		} else {
			if (!"0".equals(key)) {
				// 指定组织的用户
				users = userService.getBindHierarchyUsersPageBykey(start, length, key, null, null);
				count = userService.getBindHierarchyUsersCount(key);
			} else {
				// 所有组织的用户
				users = userService.getBindHierarchyUsersPageNone(start, length, key, "createTime", null);
				count = userService.getBindHierarchyUsersCountNone(key);
			}
		}

		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/initHierarchyTree", method = RequestMethod.GET)
	public Map<String, Object> initHierarchyTree() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Hierarchy> node = null;

		node = hierarchyService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = hierarchyService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		modelAndView = createLayoutView("userDimension/index");
		return modelAndView;
	}
}
